<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RWA Platform - Wallet Authentication Test</title>
    <script src="https://cdn.ethers.io/lib/ethers-5.7.2.umd.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #f5f5f5;
        }

        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }

        .section {
            margin: 20px 0;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }

        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }

        button:hover {
            background: #0056b3;
        }

        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        .success {
            color: #28a745;
        }

        .error {
            color: #dc3545;
        }

        .info {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
            font-family: monospace;
            font-size: 12px;
            word-break: break-all;
        }

        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
        }

        .status.success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
        }

        .status.error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>🏦 RWA Platform - Wallet Authentication Test</h1>

        <div class="section">
            <h3>1. Connect Wallet</h3>
            <button id="connectBtn" onclick="connectWallet()">Connect MetaMask</button>
            <div id="walletInfo" class="info" style="display: none;"></div>
        </div>

        <div class="section">
            <h3>2. Get Nonce</h3>
            <button id="nonceBtn" onclick="getNonce()" disabled>Get Nonce for Signing</button>
            <div id="nonceInfo" class="info" style="display: none;"></div>
        </div>

        <div class="section">
            <h3>3. Sign Message</h3>
            <button id="signBtn" onclick="signMessage()" disabled>Sign Authentication Message</button>
            <div id="signatureInfo" class="info" style="display: none;"></div>
        </div>

        <div class="section">
            <h3>4. Authenticate</h3>
            <input type="text" id="fullNameInput" placeholder="Your full name (optional)"
                style="width: 200px; padding: 5px; margin-right: 10px;">
            <button id="authBtn" onclick="authenticate()" disabled>Login to RWA Platform</button>
            <div id="authResult" class="status" style="display: none;"></div>
        </div>

        <div class="section">
            <h3>5. Test Protected Endpoint</h3>
            <button id="testBtn" onclick="testProtectedEndpoint()" disabled>Get My Profile</button>
            <div id="testResult" class="info" style="display: none;"></div>
        </div>
    </div>

    <script>
        const API_BASE_URL = 'http://localhost:3000/api';
        let currentAccount = null;
        let currentNonce = null;
        let currentMessage = null;
        let currentSignature = null;
        let authToken = null;

        // 连接钱包
        async function connectWallet() {
            if (typeof window.ethereum !== 'undefined') {
                try {
                    const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
                    currentAccount = accounts[0];

                    document.getElementById('walletInfo').innerHTML = `
                        <strong>Connected Wallet:</strong><br>
                        Address: ${currentAccount}<br>
                        Network: ${await getNetworkName()}
                    `;
                    document.getElementById('walletInfo').style.display = 'block';
                    document.getElementById('nonceBtn').disabled = false;

                    console.log('Wallet connected:', currentAccount);
                } catch (error) {
                    console.error('Failed to connect wallet:', error);
                    alert('Failed to connect wallet: ' + error.message);
                }
            } else {
                alert('MetaMask is not installed!');
            }
        }

        // 获取网络名称
        async function getNetworkName() {
            try {
                const chainId = await window.ethereum.request({ method: 'eth_chainId' });
                const networks = {
                    '0x1': 'Ethereum Mainnet',
                    '0x89': 'Polygon Mainnet',
                    '0x38': 'BSC Mainnet',
                    '0xaa36a7': 'Ethereum Sepolia',
                    '0x13881': 'Polygon Mumbai'
                };
                return networks[chainId] || `Unknown (${chainId})`;
            } catch (error) {
                return 'Unknown';
            }
        }

        // 获取随机数
        async function getNonce() {
            try {
                const response = await fetch(`${API_BASE_URL}/auth/nonce`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        walletAddress: currentAccount
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();
                currentNonce = data.nonce;
                currentMessage = data.message;

                document.getElementById('nonceInfo').innerHTML = `
                    <strong>Nonce Generated:</strong><br>
                    Nonce: ${currentNonce}<br><br>
                    <strong>Message to Sign:</strong><br>
                    ${currentMessage.replace(/\n/g, '<br>')}
                `;
                document.getElementById('nonceInfo').style.display = 'block';
                document.getElementById('signBtn').disabled = false;

                console.log('Nonce received:', data);
            } catch (error) {
                console.error('Failed to get nonce:', error);
                alert('Failed to get nonce: ' + error.message);
            }
        }

        // 签名消息
        async function signMessage() {
            try {
                const provider = new ethers.providers.Web3Provider(window.ethereum);
                const signer = provider.getSigner();

                currentSignature = await signer.signMessage(currentMessage);

                document.getElementById('signatureInfo').innerHTML = `
                    <strong>Signature Generated:</strong><br>
                    ${currentSignature}
                `;
                document.getElementById('signatureInfo').style.display = 'block';
                document.getElementById('authBtn').disabled = false;

                console.log('Message signed:', currentSignature);
            } catch (error) {
                console.error('Failed to sign message:', error);
                alert('Failed to sign message: ' + error.message);
            }
        }

        // 认证登录
        async function authenticate() {
            try {
                const fullName = document.getElementById('fullNameInput').value.trim();

                const response = await fetch(`${API_BASE_URL}/auth/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        walletAddress: currentAccount,
                        message: currentMessage,
                        signature: currentSignature,
                        fullName: fullName || undefined
                    })
                });

                const data = await response.json();

                if (!response.ok) {
                    throw new Error(data.message || `HTTP error! status: ${response.status}`);
                }

                authToken = data.data.token;
                const user = data.data.user;

                document.getElementById('authResult').className = 'status success';
                document.getElementById('authResult').innerHTML = `
                    <strong>✅ Authentication Successful!</strong><br>
                    User ID: ${user.id}<br>
                    Wallet: ${user.walletAddress}<br>
                    Name: ${user.fullName || 'Not set'}<br>
                    Role: ${user.role}<br>
                    Active: ${user.isActive}<br>
                    Created: ${new Date(user.createdAt).toLocaleString()}<br><br>
                    <strong>JWT Token:</strong><br>
                    ${authToken.substring(0, 50)}...
                `;
                document.getElementById('authResult').style.display = 'block';
                document.getElementById('testBtn').disabled = false;

                console.log('Authentication successful:', data);
            } catch (error) {
                console.error('Authentication failed:', error);
                document.getElementById('authResult').className = 'status error';
                document.getElementById('authResult').innerHTML = `
                    <strong>❌ Authentication Failed!</strong><br>
                    ${error.message}
                `;
                document.getElementById('authResult').style.display = 'block';
            }
        }

        // 测试受保护的端点
        async function testProtectedEndpoint() {
            try {
                const response = await fetch(`${API_BASE_URL}/users/me`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${authToken}`,
                        'Content-Type': 'application/json',
                    }
                });

                const data = await response.json();

                if (!response.ok) {
                    throw new Error(data.message || `HTTP error! status: ${response.status}`);
                }

                document.getElementById('testResult').innerHTML = `
                    <strong>✅ Protected Endpoint Test Successful!</strong><br>
                    <pre>${JSON.stringify(data, null, 2)}</pre>
                `;
                document.getElementById('testResult').style.display = 'block';

                console.log('Protected endpoint test successful:', data);
            } catch (error) {
                console.error('Protected endpoint test failed:', error);
                document.getElementById('testResult').innerHTML = `
                    <strong>❌ Protected Endpoint Test Failed!</strong><br>
                    ${error.message}
                `;
                document.getElementById('testResult').style.display = 'block';
            }
        }

        // 页面加载时检查MetaMask
        window.addEventListener('load', function () {
            if (typeof window.ethereum !== 'undefined') {
                console.log('MetaMask is available!');
            } else {
                alert('Please install MetaMask to use this application!');
            }
        });

        // 监听账户变化
        if (window.ethereum) {
            window.ethereum.on('accountsChanged', function (accounts) {
                if (accounts.length === 0) {
                    console.log('Please connect to MetaMask.');
                } else if (accounts[0] !== currentAccount) {
                    currentAccount = accounts[0];
                    console.log('Account changed to:', currentAccount);
                    // 重置状态
                    authToken = null;
                    document.getElementById('testBtn').disabled = true;
                }
            });
        }
    </script>
</body>

</html>